import hashlib
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from blog.models import User

def login_page_request(request):
    if request.method == 'GET':
        # 先去session看username, uuid，有，登录成功
        # 去cookies看有username, uuid，有，登录成功
        if request.session.get('username') and request.session.get('uuid'):
            return HttpResponse('已登录')
        elif request.COOKIES.get('username') and request.COOKIES.get('uuid'):
            return HttpResponse('已登录')
        else:
            return render(request, 'login.html')
    elif request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist as e:
            return HttpResponse('用户名不存在')
        md = hashlib.md5()
        # password从字符串转为字节
        md.update(password.encode())
        # password进行加密，转成16进制
        password = md.hexdigest()
        if password != user.password:
            return HttpResponse('密码错误')
        request.session['username'] = username
        request.session['uuid'] = user.id
        resp = HttpResponse('登录成功')
        if'remember' in request.POST:
            resp.set_cookie('username', username, 3600 * 24 * 7)
            resp.set_cookie('uuid', user.id, 3600 * 24 * 7)
        return resp